package cn.yangyumanage.util;

import android.content.Context;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.List;

public class Utils {

    //根据手机的分辨率从dp的单位转成px（像素）
    public static int dip2px(Context context, float dpValue) {
        //获取当前手机的像素密度（1个dp对应几个px）
        float scale = context.getResources().getDisplayMetrics().density;
        //四舍五入取整
        return (int) (dpValue * scale + 0.5f);
    }

    //汉字转拼音
    public static String toPinYin(String input) {
        StringBuilder output = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);//将拼音输出为小写字母
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//将拼音输出为不带声调的形式

        char[] inputArray = input.toCharArray();
        for (char c : inputArray) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {//如果字符是汉字
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);//将汉字转换为拼音
                    output.append(pinyinArray[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                output.append(c);
            }
        }
        return output.toString();
    }

    //Object转List
    public static <T> List<T> objectToList(Object object) {
        List<T> list = new ArrayList<>();
        if (object instanceof List<?>) {
            for (Object o : (List<?>) object) {
                list.add((T) o);
            }
        }
        return list;
    }
}
